package com.murphy.gatewaymain.function;

import com.alibaba.fastjson.JSON;
import com.murphy.gatewaymain.response.BaseResponse;
import com.murphy.gatewaymain.utils.SignUtil;
import lombok.extern.log4j.Log4j2;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * 解密
 * @author dongsufeng
 * @date 2021/11/9 14:09
 * @version 1.0
 */
@Component
@Log4j2
public class GongShangDecryptFunction implements RewriteFunction<BaseResponse, String> {
	@Override
	public Publisher<String> apply(ServerWebExchange exchange, BaseResponse baseResponse) {
		log.info("返回解密={}",JSON.toJSONString(baseResponse));
		if (exchange.getRequest().getMethodValue().equals(HttpMethod.GET.name())){
			return Mono.just(JSON.toJSONString(baseResponse));
		}
		try {
			if (!baseResponse.success()){
				baseResponse.setCode("100001");
				baseResponse.setMsg("失败");
				return Mono.just(JSON.toJSONString(baseResponse));
			}
			String key_ = SignUtil.decryptByPrivateKey4Pkcs5(baseResponse.getRandomKey().getBytes(StandardCharsets.UTF_8), GongShangEncryptFunction.privateKey);
			Object data = baseResponse.getData();
			String s = SignUtil.decrypt4Base64(data instanceof String ? data.toString() : JSON.toJSONString(data) , key_);
			return Mono.just(s);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return Mono.empty();
	}
}
